<?php

namespace App\Exceptions;

use App\Components\Admin\ResponseHelper;
use App\Helpers\RequestHelper;
use Exception;
use Psr\Http\Message\ResponseInterface;
use Slim\Exception\HttpException;
use Slim\Handlers\ErrorHandler;
use Throwable;

class HttpErrorHandler extends ErrorHandler
{
    protected function respond(): ResponseInterface
    {
        $exception = $this->exception;
        $statusCode = 500;
        $title = 'SERVER_ERROR';
        $describe = 'An internal error has occurred while processing your request.';

        if ($exception instanceof HttpException) {
            $statusCode = $exception->getCode();
            $title = $exception->getMessage();
            $describe = $exception->getDescription();
        } elseif ($exception instanceof Exception || $exception instanceof Throwable) {
            $title = $exception->getMessage();
            $describe = 'File: ' . $exception->getFile();
            $describe .= '; Line: ' . $exception->getLine();
        }

        $error = [
            'status_code' => $statusCode,
            'title' => $title,
            'describe' => $describe,
        ];

        $response = $this->responseFactory->createResponse($statusCode);

        if (RequestHelper::isAjax() === true) {
            $response = $response->withHeader('Content-Type', 'application/json');
            $response->getBody()->write(json_encode($error, JSON_PRETTY_PRINT));
        } else {
            $twig = ResponseHelper::createTwig();
            $response->getBody()->write($twig->fetch('admin/error.html', [
                'title' => $title,
                'error' => $error,
            ]));
        }

        if ($this->displayErrorDetails !== true) {
            if ($statusCode !== 404) {
                $error['request'] = [
                    'target' => $this->request->getRequestTarget(),
                    'method' => $this->request->getMethod(),
                    'params' => $this->request->getQueryParams(),
                    'cookies' => $this->request->getCookieParams(),
                    'bodys' => $this->request->getParsedBody(),
                ];
                $this->logger->error('request error', $error);
            }
        }

        return $response;
    }
}
